//
//  OnMarkThirdViewController.m
//  BSLCar
//
//  Created by 梁毅 on 15/6/1.
//  Copyright (c) 2015年 lyz. All rights reserved.
//

#import "OnMarkThirdViewController.h"
#import <UIImageView+WebCache.h>
#import <SDImageCache.h>
@interface OnMarkThirdViewController ()
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;
@property (nonatomic, retain) NSMutableArray *firArray;
@property (nonatomic, retain) NSMutableArray *secArray;
@property (nonatomic, retain) NSMutableArray *secondArray;
@property (nonatomic, retain) UIView *tableHearView;
@end
@implementation OnMarkThirdViewController
- (void)dealloc
{
    [_str release];
    [_titleName release];
    [_dataArray release];
    [_strShoucang release];
    [_shoucangArray release];
    [_activityIndicator release];
    [_firArray release];
    [_secArray release];
    [_secondArray release];
    [_tableHearView release];
    [super dealloc];
}
- (void)getResult
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *cityID = [user objectForKey:@"cityid"];
    NSString *provinceId = nil;
    if ([cityID isEqualToString:@"0"]) {
        provinceId = cityID;
    } else{
        provinceId = [cityID substringToIndex:2];
        provinceId = [NSString stringWithFormat:@"%@0000",provinceId];
    }
    self.dataArray = [NSMutableArray array];
    NSString *str1 =[NSString stringWithFormat:@"http://baojia.qichecdn.com/priceapi3.9.2/services/specsummary/get?cityid=%@&myLat=0&myLon=0&order=0&pageindex=1&pagesize=20&provinceid=%@&specid=%@",cityID,provinceId, self.str];
    str1 = [str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 
    NSURL *url = [NSURL URLWithString:str1];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!connectionError) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dic1 = [dic objectForKey:@"result"];
            
            OnMarketForthModel *model1 = [OnMarketForthModel getModel];
            model1.logo = [dic1 objectForKey:@"logo"];
            model1.isTrue = NO;
            model1.fctname = [dic1 objectForKey:@"fctname"];
            model1.piccount = [dic1 objectForKey:@"piccount"];
            
            model1.levelname = [dic1 objectForKey:@"levelname"];
            
            NSArray *array1 = [dic1 objectForKey:@"dealerlist"];
            for (NSDictionary *dic2  in array1) {
                OnMarketForthModel *model = [OnMarketForthModel getModel];
                model.cityid = [dic2 objectForKey:@"cityid"];
                //   NSLog(@"%@",model.cityid);
                model.dealeraddress = [dic2 objectForKey:@"dealeraddress"];
                model.dealerprice = [dic2 objectForKey:@"dealerprice"];
                
                model.dealershortname = [dic2 objectForKey:@"dealershortname"];
                
                model.orderrange = [dic2 objectForKey:@"orderrange"];
                [self.dataArray addObject:model];
            }
            [self.dataArray addObject:model1];
            
            [self.activityIndicator stopAnimating];
            [self creatView];
        }
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.title =[NSString stringWithFormat:@"%@", self.title];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.dataArray = [NSMutableArray array];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] init];
    item.title = @"返回";
    self.navigationItem.backBarButtonItem = item;
    [item release];
    
    myTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 165, self.view.frame.size.width, self.view.frame.size.height - 230) style:UITableViewStylePlain];
    
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.activityIndicator.color = [UIColor grayColor];
    self.activityIndicator.center = self.view.center;
    [self.view addSubview:self.activityIndicator];
    [self.activityIndicator startAnimating];
    
    [self getResult];
    
    [_activityIndicator release];
}

- (void)creatView {
    myTable.delegate = self;
    myTable.dataSource = self;
    [self.view addSubview:myTable];
    
    OnMarketForthModel *model1 = [self.dataArray lastObject];
    self.tableHearView = [[UIView alloc] initWithFrame:CGRectMake(0, -15, self.view.bounds.size.width, 180)];
    [self.view addSubview:self.tableHearView];
    NSURL *URL = [NSURL URLWithString:model1.logo];
//    NSData *data = [NSData dataWithContentsOfURL:URL];
//    UIImage *image = [UIImage imageWithData:data];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.tableHearView.frame.size.width, self.tableHearView.frame.size.height)];
//    imageView.image = image;
    [imageView sd_setImageWithURL:URL placeholderImage:[UIImage imageNamed:@"Bei"]];
    [self.tableHearView addSubview:imageView];
    myTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(self.view.bounds.size.width - 115, 15, 100, 60);
    button.titleLabel.textAlignment = NSTextAlignmentRight;
    button.titleLabel.numberOfLines = 0;
    [button.titleLabel sizeToFit];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitle:[NSString stringWithFormat:@"%@张图片", model1.piccount] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *buttonNull = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonNull.frame = self.tableHearView.frame;
    buttonNull.backgroundColor = [UIColor clearColor];
    [buttonNull addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(self.view.bounds.size.width - self.view.bounds.size.width / 3 - 42, 158, self.view.bounds.size.width / 3 + 40, 20)];
    label.text = [NSString stringWithFormat:@"%@/%@",model1.fctname, model1.levelname];
    self.titleName = model1.levelname;
    label.textAlignment  = 1;
    label.font = [UIFont systemFontOfSize:12];
    label.backgroundColor = [UIColor purpleColor];
    [self.tableHearView addSubview:label];
    [self.tableHearView addSubview:button];
    [self.tableHearView addSubview:buttonNull];
    
    [_tableHearView release];
    [myTable release];
}
- (void)click:(UIButton *)sender {
    LastComViewController *lastview = [[LastComViewController alloc] init];
    [self.navigationController pushViewController:lastview animated:YES];
    lastview.serid = @"0";
    lastview.name = self.titleName;
    lastview.sp = self.str;
    [lastview release];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    OnMarketForthTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[OnMarketForthTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    OnMarketForthModel *model = [self.dataArray objectAtIndex:indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.lablelName.text =model.dealershortname;
    cell.labelprice.text = [NSString stringWithFormat:@"%@万",model.dealerprice];
    cell.lablelAddress.text =model.dealeraddress;
    self.strShoucang = cell.lablelName.text;
    model.title = self.title;
    cell.button.tag = indexPath.row;
    NSArray *array2 = [CollectDataBaseManager selectData];
    
    [cell.button addTarget:self action:@selector(shoucang:) forControlEvents:UIControlEventTouchUpInside];
    
    for (OnMarketForthModel *model1 in array2) {
        if ([model.dealerprice isEqualToString:model1.dealerprice] && [model.dealershortname isEqualToString:model1.dealershortname]) {
            [cell.button setImage:[UIImage imageNamed:@"iconfont-shoucang-2"]  forState:UIControlStateNormal];
            return cell;
        }
    }
    [cell.button setImage:[UIImage imageNamed:@"iconfont-shoucang"]  forState:UIControlStateNormal];
    return cell;
}
- (void)shoucang:(UIButton *)button1
{
    [CollectDataBaseManager openDataBase];
    [CollectDataBaseManager createTabel];
    OnMarketForthModel *model = [self.dataArray objectAtIndex:button1.tag];
    
    if (button1.selected == NO) {
        [button1 setImage:[UIImage imageNamed:@"iconfont-shoucang-2"] forState:UIControlStateNormal];
         NSArray *array2 = [CollectDataBaseManager selectData];
        BOOL isExist = NO;
        for (OnMarketForthModel *model1 in array2) {
            if ([model.dealerprice isEqualToString:model1.dealerprice] && [model.dealershortname isEqualToString:model1.dealershortname]) {
                isExist = YES;
                break;
            }
        }
        if (!isExist) {
            [CollectDataBaseManager insertValue:model];
        }

        button1.selected = YES;
    }
    else
    {
        [button1 setImage:[UIImage imageNamed:@"iconfont-shoucang"] forState:UIControlStateNormal];
        [CollectDataBaseManager deleteValue:model];
        button1.selected = NO;

    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count - 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
